import Vue from 'vue';
import axios from 'axios';
import jwtDecode from 'jwt-decode'
// import { TOKEN_NAME } from '@/config/global';
import { getRemoteUserInfoAPI, login } from '@/api/requestApi';
import store from '..';

const TOKEN_NAME = 'access_token';
const USER_NAME = 'user_name';

const InitUserInfo = {
  name: '',
  roles: [],
};

interface data {
  access_token: string,
  token_type: string
}

interface loginResData {
  code: string,
  msg: string,
  data: data
}
// 定义的state初始值
const state = {
  token: localStorage.getItem(TOKEN_NAME), // 默认token不走权限
  userInfo: InitUserInfo,
};

const mutations = {
  setToken(state, token):void {
    localStorage.setItem(TOKEN_NAME, token);
    state.token = token;
  },
  setUserName(state, username):void {
    localStorage.setItem(USER_NAME, username);
    state.username = username;
  },
  removeToken(state):void  {
    localStorage.removeItem(TOKEN_NAME);
    state.token = '';
  },
  removeUserName(state):void {
    localStorage.removeItem(USER_NAME);
    state.username = '';
  },
  setUserInfo(state, userInfo):void  {
    state.userInfo = userInfo;
  },
};

const getters = {
  token: (state) => state.token,
  roles: (state) => state.userInfo?.roles,
};

// const actions = {
//   async login({commit},{apiUrl, req, headers}){
//     await axios.post(apiUrl,req,headers).then(res => {
//       if (res.data.code === '000') {
//         Vue.prototype.$message.success('登录成功');
//         // this.$message.success('已恢复初始设置');
//         localStorage.setItem(TOKEN_NAME, res.data.data.access_token);
//         // commit('setToken', res.data.data.access_token);
//         setTimeout(() => {
//           // Vue.prototype.$router.replace('/').catch(() => '');
//           router.push('/')
//         }, 1000);
//       }
//     })
//   },
const actions = {
  async login({ commit }, userInfo):Promise<any> {
    return new Promise((resolve, reject) => {
      const loginAPI = login()
      const headers = {headers: {'Content-Type': 'application/x-www-form-urlencoded'}}
      const reqParam = new FormData();
      reqParam.append('grant_type', 'password');
      reqParam.append('username', userInfo.username);
      reqParam.append('password', userInfo.password);
      axios.post(loginAPI,reqParam,headers).then(res => {
        if (res.status === 200) {
          if (res.data.code === '000'){
            commit('setToken', res.data.data.access_token);
            commit('setUserName', userInfo.username);     
          }
          resolve(res.data)  
        }        
      }).catch(error =>{
        reject(error)
      })
    })
  },
  async logout({ commit }) {
    commit('removeToken');
    commit('removeUserName');
    commit('setUserInfo', InitUserInfo);
  },
  async getUserInfo({ commit, state }) {
    // const token = localStorage.getItem('access-token')
    const getRemoteUserInfo = async (token) => {
      // const decodedToken = jwtDecode(token)
      // console.log('token-->', decodedToken)
      axios.get(getRemoteUserInfoAPI(), {
        headers:{
          'content-type': 'application/json',
          // 'Authorization': localStorage.getItem('access_token'),
          'Authentication': localStorage.getItem('access_token')
        }})
        .then((res) => {
          console.log('userInfo--->', res.data)
          if (res.data.code === 401) {
            commit('removeToken');
            commit('removeUserName');
            commit('setUserInfo', InitUserInfo);
            
          }
        })
      return {
        name: 'td_main',
        roles: ['ALL_ROUTERS'],
      };
    };
    const mockRemoteUserInfo = async (token) => {
      if (token === 'main_token') {
        return {
          name: 'td_main',
          roles: ['ALL_ROUTERS'],
        };
      }
      return {
        name: 'td_dev',
        roles: ['UserIndex', 'DashboardBase', 'login'],
      };
    };

    // const res = await mockRemoteUserInfo(state.token);
    // console.log('state.token----->',state.token)
    const res = await getRemoteUserInfo(state.token);
    // console.log('res----->',res)

    commit('setUserInfo', res);
  },

  // checkToken({ commit }) {
  //   const token = localStorage.getItem('token');
  //   if (token) {
  //     // 将token保存到Vuex中
  //     commit('SET_TOKEN', token);
  //   } else {
  //     // 如果没有token，则重定向到登录页面
  //     router.push('/');
  //   }
  // },
  // getToken(){
  //   console.log("我被调用了")
  //   return this.state.token;
  // }
};


export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters,
};
function logout() {
  throw new Error('Function not implemented.');
}

